<template>
    <div class="loan-in-detail-me" v-if='pageLoaded'>
        <!-- wrapper -->
        <div class="wrapper">
            <div class="loan-detail-header" v-if='userInfo.user'>
                <div class="loan-detail-user" @click='goContactDetail(userInfo.user.uuid)'>
                    <span class="loan-detail-user__avatar"><img :src="userInfo.user.avatar || placeholderImg" alt=""></span>
                    <div class="loan-detail-user__info">
                        <p class='name'>
                            <span>{{userInfo.user.realName}}</span>
                            <img v-if='userInfo.isContact' width="16" height='16' src="../images/contactloan.png"></p>
                        <p>{{userInfo.user.mobile}}</p>
                    </div>
                    <div class="user-operation__item" @click.stop='add' v-if='!userInfo.isContact'>
                        <span class='user-operation__logo contact'></span>
                        <p class='font-caption'>加联系人</p>
                    </div>
                    <!-- <div class="user-operation__item">
                        <span class='user-operation__logo chat'></span>
                        <p class='font-caption'>发消息</p>
                    </div> -->
                    <div class="user-operation__item" @click.stop="goReportDetail">
                        <span class='user-operation__logo report'></span>
                        <p class='font-caption'>信用报告</p>
                    </div>
                </div>
                <ul class="loan-detail-money__list">
                    <li class="loan-detail-money__item">
                        <span class='persent'>{{userInfo.waitReceiveAmount | toYuan}}</span>
                        <p>待收金额</p>
                    </li>
                    <li class="loan-detail-money__item">
                        <span class='persent'>{{userInfo.waitReceiveAmount | toYuan}}</span>
                        <p>待还金额</p>
                    </li>
                    <li class="loan-detail-money__item">
                        <span class='persent'>{{ userInfo.lendTime }}</span>
                        <p>出借次数</p>
                    </li>
                </ul>
            </div>

            <div class="loan-detail-main" :class='{lend : userInfo.user}'>
                <div class="loan-detail-number">
                    <p class="loan-detail-number__number">编号: {{ number }}</p>
                    <span class="loan-detail-number__status" >有效期: <count-down :date='detail.borrowEffectiveTime'></count-down></span>
                </div>
                <div class="loan-detail-money">
                    <div class="loan-detail-money__total">
                        <p class='text'>借款总额</p>
                        <span class='number'>{{ detail.borrowAmount | toYuan }}元</span>
                    </div>
                    <ul class="loan-detail-money__list">
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{ detail.yearRate / 100 }}%</span>
                            <p>年化利率</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{ detail.serviceFee | toYuan }}</span>
                            <p>服务费(元)</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{ detail.interestAmount | toYuan }}</span>
                            <p>预计利息(元)</p>
                        </li>
                    </ul>
                </div>
                <div class="loan-detail-info">
                    <ul class="card__info">
                        <li class="card__info-item">发布日期：{{ detail.createdAt | dateFormat }}</li>
                        <li class="card__info-item">还款方式：{{ detail.repayWayStr }}</li>
                        <li class="card__info-item">借款时长：{{detail.borrowDays}}{{detail.daysTypeStr}}</li>
                        <li class="card__info-item">借款用途：{{ detail.borrowUsage }}</li>
                        <li class="card__info-item">所有人可见：{{ detail.public | booleanToStr }}</li>
                    </ul>
                    <!-- <p class="card__info-item full">补充说明：{{ detail.addSay || placeholder }}</p> -->
                    <template v-if='detail.imageSay && detail.imageSay.length'>
                        <div class="card__info-item">图片说明：</div>
                        <ul class="loan-detail-info__pics">
                            <li class="loan-detail-info__pic" v-for='item in detail.imageSay' @click='imgViewShow(item.url)'>
                                <img :src="item.url">
                            </li>
                        </ul>
                    </template>
                    <div class="loan-detail-agreement"><span class="button short pure" @click='showAgreement = true'>查看借款协议</span></div>
                </div>
            </div>
        </div>

        <confirm 
            v-if='userInfo.user'
            :show='show_contact_add'
            @close='show_contact_add = false'
            @confirm='applyContact'
            :tips='`需要发送申请给${userInfo.user.realName}`'
            title='添加联系人申请'>
                <textarea class="confirm-textarea" placeholder="例如: 我想向你借款" rows='2' v-model='applyReason'></textarea>
        </confirm>

        <footer class="footer-button" v-if='detail.isMyPublishBorrow'>
            <span class="button transparent" @click='show_modal_close_loan = true'>关闭借款</span>
            <span class="button" v-if='!userInfo.user' @click='showShare'>分享借款</span>
        </footer>
        <footer class="single-button" v-if='detail.isMyApplyBorrow'>
            <span class="button transparent" @click='show_modal_close_loan = true'>关闭借款</span>
        </footer>

        <image-view :url='currentImg' :show='modal_img_show' @close='modal_img_show = false'></image-view>

        <confirm 
            :show='show_modal_close_loan'
            @close='show_modal_close_loan = false'
            @confirm='closeLoan'
            title='确认关闭借款'
            tips='是否确认关闭该借款'></confirm>

        <agreement
            :show='showAgreement'
            @close='showAgreement=false'></agreement>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import confirm from '../components/Confirm.vue'
    import countDown from '../components/CountDown.vue'
    import toYuan from '../filters/filter-toYuan'
    import imageView from '../components/ImageView.vue'
    import dateFormat from '../filters/filter-dateFormat'
    import booleanToStr from '../filters/filter-booleanToStr'
    import agreement from '../components/Agreement.vue'
    import  { mapGetters, mapActions }  from 'vuex'
    import { loanInApi, loanOutApi, contactApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            confirm,
            countDown,
            agreement,
            imageView
        },
        filters:{
            toYuan,
            dateFormat,
            booleanToStr
        },
        data() {
            return {
                number:this.$route.params.number,
                pageLoaded:false,
                applyReason:'',
                placeholder:'--',
                placeholderImg:require('../images/loading_1.png'),
                detail:{},
                userInfo:{},
                show_modal_close_loan:false,
                show_contact_add:false,
                showAgreement:false,
                modal_img_show:false,
                currentImg:'',
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo',
            ]),
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
            hasUserCount(){
                return !_.isEmpty(this.userCount)
            },
            noEditObject(){
                return _.isEmpty(this.editObject)
            },
            noInvoiceInfo(){
                return _.isEmpty(this.invoiceInfo)
            }
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setShare',
                'showShare'
            ]),

            // function
            add(){
                this.showLoading()
                contactApi.judge({
                    mobile:this.userInfo.user.uuid
                })
                .then(result=>{
                    this.show_contact_add = true
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            applyContact(){
                this.showLoading()
                contactApi.apply({
                    mobile:this.userInfo.user.uuid,
                    applyReason:this.applyReason
                })
                .then(result=>{
                    this.hideLoading()
                    this.show_contact_add = false
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            goContactDetail(id){
                this.$router.push({
                    name:'contact-detail',
                    params:{
                        id:id
                    },
                    query:{
                        type:'lend'
                    }
                })
            },
            share(item){
                let protocol = location.protocol
                let host = location.host
                let pathname = location.pathname
                let search = location.search

                let realUrl = `${protocol}//${host}${pathname}${search}#share-loan-in/${item.borrowNo}`
                this.setShare({
                    message:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () { 

                        },
                        cancel: function () { 

                        }
                    },
                    timeline:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                    qq:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                })
            },
            goReportDetail(){
                if(!this.userInfo.creditReport){
                    this.setMsgTip({
                        text:'该用户暂无信用报告！',
                        type:'warn'
                    })
                    return
                }
                this.$router.push({
                    name:'user-credit-report-detail',
                    params:{
                        no:this.userInfo.creditReport.creditReportNo
                    }
                })
            },
            closeLoan(){
                this.showLoading()
                loanInApi.close({
                    borrowNo:this.number
                })
                .then(result=>{
                    this.hideLoading()
                    this.$router.push({
                        name:'loan-in-index'
                    })
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            imgViewShow(url){
                this.currentImg = url
                this.modal_img_show = true
            },
            getDetail(){
                return loanInApi.detail({
                    borrowNo:this.number
                })
                .then(result=>{
                    this.share(result)
                    this.detail = result
                })
            },
            getUserInfo(lendNo){
                return loanOutApi.userInfo({
                    lendNo:lendNo
                })
                .then(result=>{
                    this.userInfo = result
                })
            },
        },
        created(){

            this.showLoading()
            let lendNo = this.$route.query.lendNo
            
            if(!lendNo){
                this.getDetail()
                .then(result=>{
                    this.pageLoaded = true
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.pageLoaded = true
                    this.hideLoading()
                })
            }
            else{
                Promise.all([this.getUserInfo(lendNo), this.getDetail()])
                .then(result=> {
                    this.pageLoaded = true
                    this.hideLoading()
                })
                .catch(error=> {
                    console.error(error);
                    this.pageLoaded = true
                    this.hideLoading()
                });
            }
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-in-detail-me{
        .wrapper{
            padding-bottom: 100px;
        }
        .loan-detail-main{
            background-color: #fff;
            padding:0 24px 0 24px;
            position: relative;
            &.lend{
                margin-top: 16px;
            }
        }
        .loan-detail-repayment{
            padding-top: 52px;
        }
        .repayment-tab{
            display: flex;
            background-color: #fff;
        }
        .repayment-tab__item{
            flex:1;
            text-align: center;
            padding:10px 0 8px 0;
            position: relative;
            &:after{
                content:'';
                transition:ease 150ms transform;
                transform:scale(0);
                border-top:2px solid $orange;
                position: absolute;
                bottom:0;
                left:16px;
                right:16px;
            }
            &:active,&.active{
                &:after{
                    transform:scale(1);
                }
            }
            .title{
                @extend %font-title;
                color:$importColor;
            }
            .money{
                @extend %font-caption;
            }
        }
        .repayment-detail{
            text-align: center;
        }
        .repayment-detail__item{
            @extend %font-caption;
            color:$importColor;
            background-color: #fff;
            &.head{
                color:$defaultColor;
                font-weight: 400;
                background-color: transparent;
            }
            display: flex;
            padding: 0 24px;
            border-top:1px solid $sectionColor;
        }
        .repayment-detail__value{
            width: 20%;
            flex:1;
            box-sizing:border-box;
            padding: 14px 0 14px 0;
            &:first-child{
                padding-left: 0;
            }
        }
        .modal-repayment-detail{

        }
        .modal-repayment-detail__header{
            display: flex;
            justify-content: space-between;
            padding-bottom: 8px;
            border-bottom: 1px solid $sectionColor;
        }
        .modal-repayment-detail__period{
            .period{
                @extend %font-body1;
                color:$importColor;
            }
            .time{
                @extend %font-caption;
            }
        }
        .modal-repayment-detail__money{
                @extend %font-title;
                color:$importColor;
        }
        .modal-repayment-detail__main{
            padding-top: 8px;
        }
        .modal-repayment-detail__item{
            padding-top: 8px;
            display: flex;
            justify-content: space-between;
            .key{
                @extend %font-body1;
                color:$importColor;
            }
            .value{
                @extend %font-caption;
            }
        }
    }

</style>
